import { app, shell, BrowserWindow, Tray, Menu, nativeImage, ipcMain, globalShortcut } from 'electron'
import path from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import trayIcon from '../../resources/logo-gray.png?asset'
import { verticalEdge, getConfig, getIp, fadeInWindow, minWidth, minHeight } from './edging'

let tray: Tray
let mainWindow: BrowserWindow
const width = 290
const height = 300
let onShow = true
let edge: false | 'n' | 'l' | 'r' = false
// let sys = process.platform === 'darwin' ? 'mac' : 'win'

const menu = Menu.buildFromTemplate([
  {
    label: '设置',
    click: () => {
      if (!mainWindow.isVisible()) {
        fadeInWindow(mainWindow, 'in')
      }
      mainWindow.webContents.send('settings', 'settings')
    },
    accelerator: process.platform === 'darwin' ? 'Cmd+,' : 'Alt+Shift+S'
  },
  {
    label: '天气',
    click: () => {
      if (!mainWindow.isVisible()) {
        fadeInWindow(mainWindow, 'in')
      }
      mainWindow.webContents.send('settings', 'home')
    },
    accelerator: process.platform === 'darwin' ? 'Cmd+.' : 'Alt+Shift+T'
  },
  {
    type: 'separator',
  },
  {
    label: '退出',
    click: () => {
      app.exit()
    },
    accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Alt+Shift+I'
  }
])

function createWindow(): void {
  mainWindow = new BrowserWindow({
    width,
    height,
    show: false,
    autoHideMenuBar: true,
    frame: false,
    transparent: true,
    backgroundColor: '#00000000',
    resizable: false,
    opacity: 0,
    ...(process.platform === 'linux' ? { icon: trayIcon } : {}),
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, '../preload/index.js'),
      sandbox: false,
      devTools: true,
      scrollBounce: true,
    }
  })

  mainWindow.on('ready-to-show', async () => {
    mainWindow.setSkipTaskbar(true)
    fadeInWindow(mainWindow, 'in')
    const exePath = app.isPackaged ? path.dirname(app.getPath('exe')) : app.getAppPath()
    const file = (app.isPackaged && process.platform === 'darwin') ? '../config.json' : "./config.json"
    const config = getConfig(path.join(exePath, file))
    mainWindow.webContents.send('config', config)
    const add = await getIp(config)
    mainWindow.webContents.send('address', add)
    setInterval(() => {
      mainWindow.webContents.send("update")
    }, 1000 * 60 * 4)
    mainWindow.setAlwaysOnTop(true)
    globalShortcut.register('CmdOrCtrl+Shift+J', () => {
      if (!mainWindow.isVisible()) {
        fadeInWindow(mainWindow, 'in')
      }
      mainWindow.webContents.send('settings', 'home')
    })
  })

  // 点击关闭时，不关闭窗口而是隐藏
  mainWindow.on('close', (e) => {
    // mainWindow.hide()
    fadeInWindow(mainWindow, 'out')
    mainWindow.setSkipTaskbar(true)
    e.preventDefault()
  })
  const image = nativeImage.createFromPath(trayIcon)
  image.setTemplateImage(true)
  tray = new Tray(image)

  tray.setToolTip('天气')
  tray.setContextMenu(menu)
  tray.on('click', (_e, _r, _) => {
    if (!mainWindow.isVisible()) {
      fadeInWindow(mainWindow, 'in')
    }
  })

  // mainWindow.on('blur', () => {
  //   !onShow && fadeInWindow(mainWindow, 'out')
  // })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.webContents.openDevTools()
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'))
  }

  mainWindow.on("moved", () => {
    edge = verticalEdge(mainWindow)
    onShow = (edge && (edge != 'n'))
  })

  ipcMain.on('mouseover', (_e, val: boolean) => {
    if (val === true) {
      const size = mainWindow.getBounds()
      edge == 'l' && mainWindow.setSize(width, height, true)
      edge == 'r' && mainWindow.setBounds({
        x: size.x + size.width - width,
        width, height
      }, true)
    }
    if (val === false) {
      const size = mainWindow.getBounds()
      edge == 'l' && mainWindow.setBounds({ width: minWidth, height: minHeight }, true)
      edge == 'r' && mainWindow.setBounds({
        x: size.x + size.width - minWidth,
        width: minWidth, height: minHeight
      }, true)
    }
  })
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
